package com.agile.major.web.rest;

import com.agile.major.domain.BaseMajor;
import com.agile.major.security.AuthoritiesConstants;
import com.agile.major.security.SecurityUtils;
import com.agile.major.service.BaseMajorService;
import com.agile.major.web.rest.util.HeaderUtil;
import com.agile.major.web.rest.util.PaginationUtil;
import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;

/**
 * REST controller for managing BaseMajor.
 */
@RestController
@RequestMapping("/api")
public class BaseMajorResource {

    private final Logger log = LoggerFactory.getLogger(BaseMajorResource.class);

    private static final String ENTITY_NAME = "baseMajor";

    private final BaseMajorService baseMajorService;

    public BaseMajorResource(BaseMajorService baseMajorService) {
        this.baseMajorService = baseMajorService;
    }

    /**
     * POST  /base-majors : Create a new baseMajor.
     *
     * @param baseMajor the baseMajor to create
     * @return the ResponseEntity with status 201 (Created) and with body the new baseMajor, or with status 400 (Bad Request) if the baseMajor has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/base-majors")
    @Timed
    public ResponseEntity<BaseMajor> createBaseMajor(@RequestBody BaseMajor baseMajor) throws URISyntaxException {
        log.debug("REST request to save BaseMajor : {}", baseMajor);
        if (baseMajor.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new baseMajor cannot already have an ID")).body(null);
        }
        BaseMajor result = baseMajorService.save(baseMajor);
        return ResponseEntity.created(new URI("/api/base-majors/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /base-majors : Updates an existing baseMajor.
     *
     * @param baseMajor the baseMajor to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated baseMajor,
     * or with status 400 (Bad Request) if the baseMajor is not valid,
     * or with status 500 (Internal Server Error) if the baseMajor couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/base-majors")
    @Timed
    public ResponseEntity<BaseMajor> updateBaseMajor(@RequestBody BaseMajor baseMajor) throws URISyntaxException {
        log.debug("REST request to update BaseMajor : {}", baseMajor);
        if (baseMajor.getId() == null) {
            return createBaseMajor(baseMajor);
        }
        BaseMajor result = baseMajorService.save(baseMajor);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, baseMajor.getId().toString()))
            .body(result);
    }

    /**
     * GET  /base-majors : get all the baseMajors.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of baseMajors in body
     */
    @GetMapping("/base-majors")
    @Timed
    public ResponseEntity<Page<BaseMajor>> getAllBaseMajors(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of BaseMajors");
        Page<BaseMajor> page = baseMajorService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/base-majors");
        return new ResponseEntity<>(page, headers, HttpStatus.OK);
    }

    @GetMapping("/base-majors/role")
    @Timed
    public ResponseEntity getRoleBaseMajors(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of RoleBaseMajors");
        //获取当前教工号
        String loginname=SecurityUtils.getCurrentUserLogin().orElse(null);
        String roles=SecurityUtils.getCurrentUserJWT();
        log.debug("current user is >>"+loginname+"; current roles are >>"+roles);

        if(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.SUPERADMIN) ||SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)){//如果是超级管理员或者校领导，返回所有专业
            Page<BaseMajor> page = baseMajorService.findAll(pageable);
            HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/base-majors/role");
            return new ResponseEntity<>(page, headers, HttpStatus.OK);
        }
        else if(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.MAJOR) && SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.SUBADMIN)){
            try{
                Page<BaseMajor> page=null;
                if(pageable==null){
                   page = baseMajorService.findMajorBySubadminAndTeacher(loginname);
                }else{
                    page = baseMajorService.findMajorBySubadminAndTeacherPaper(loginname,pageable);
                }

                HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/base-majors/role");
                return new ResponseEntity<>(page, headers, HttpStatus.OK);
            }catch(Exception e){
                log.error(e.getMessage());
                return ResponseEntity.badRequest().body(e.getMessage());
            }

        }else{
            if(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.MAJOR) && !SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.SUBADMIN)){ //如果是专业带头人，查看与自己相关的专业
                try {
                    Page<BaseMajor> page=null;
                    if(pageable==null){
                        page = baseMajorService.findMajorByTeacher(loginname);
                    }else{
                        page = baseMajorService.findMajorByTeacherPaper(loginname,pageable);
                    }
                    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/base-majors/role");
                    return new ResponseEntity<>(page, headers, HttpStatus.OK);
                }catch(Exception e){
                    log.error(e.getMessage());
                    return ResponseEntity.badRequest().body(e.getMessage());
                }
            }
            else if (SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.SUBADMIN) && !SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.MAJOR)){ //如果是二级院领导，查看本院专业
                try{
                    Page<BaseMajor> page=null;
                    if(pageable==null){
                        page = baseMajorService.findMajorBySubadmin(loginname);
                    }else {
                        page = baseMajorService.findMajorBySubadminPaper(loginname, pageable);
                    }
                    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/base-majors/role");
                    return new ResponseEntity<>(page, headers, HttpStatus.OK);
                }catch(Exception e){
                    log.error(e.getMessage());
                    return ResponseEntity.badRequest().body(e.getMessage());
                }

            }
        }

        return ResponseEntity.badRequest().body("未找到对应角色");
    }

    /**
     * GET  /base-majors/:id : get the "id" baseMajor.
     *
     * @param id the id of the baseMajor to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the baseMajor, or with status 404 (Not Found)
     */
    @GetMapping("/base-majors/{id}")
    @Timed
    public ResponseEntity<BaseMajor> getBaseMajor(@PathVariable Long id) {
        log.debug("REST request to get BaseMajor : {}", id);
        BaseMajor baseMajor = baseMajorService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(baseMajor));
    }

    /**
     * DELETE  /base-majors/:id : delete the "id" baseMajor.
     *
     * @param id the id of the baseMajor to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/base-majors/{id}")
    @Timed
    public ResponseEntity<Void> deleteBaseMajor(@PathVariable Long id) {
        log.debug("REST request to delete BaseMajor : {}", id);
        baseMajorService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }
}
